package com.cyandpos.pad.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.cyandpos.pad.R;
import com.cyandpos.pad.codedcoupon.CodedCouponPresenter;
import com.cyandpos.pad.codedcoupon.ICodedCouponView;
import com.cyandpos.pad.codedcoupon.adapter.CodedCouponAdapter;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.SktConfigIdCrmConstant;
import com.cyandpos.pad.common.swipemanager.SwipeCardCommon;
import com.cyandpos.pad.posdata.CodeCoupon;
import com.cyandpos.pad.posdata.CodedCouponData;
import com.cyandpos.pad.posdata.QueryMemberRequest;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.MessageLog;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 编码券
 **/
public class CodedCouponActivity extends BaseActivity implements ICodedCouponView,TextView.OnEditorActionListener,AdapterView.OnItemClickListener  , SwipeCardCommon.DoAfterSwipeCard {
    @BindView(R.id.rl_close)
   RelativeLayout rl_close;
    @BindView(R.id.et_coded_coupon)
    EditText etCodedCoupon;
    @BindView(R.id.iv_swipe_get_coded_coupon)
    ImageView ivSwipeGetCodedCoupon;
    @BindView(R.id.tv_used_totalMoney)
    TextView tvUsedTotalMoney;
    @BindView(R.id.tv_order_totalMoney)
    TextView tvOrderTotalMoney;
    @BindView(R.id.ll_payed_info)
    LinearLayout llPayedInfo;
    @BindView(R.id.lv_coded_coupon)
    ListView lvCodedCoupon;
    @BindView(R.id.ll_vip_card_coded_coupon)
    LinearLayout llVipCardCodedCoupon;
    @BindView(R.id.btn_codedcoupon_commit)
    Button btnCodedcouponCommit;
    @BindView(R.id.btn_coded_coupon_saoma)
    Button btnSaoma;
    @BindView(R.id.member_soft_keyboard)
    SelfNumKeyView sf_containt;
    private Context mContext;
    public TicketInfo mTicket;
    private int payableMoney = 0;
    private int payId ;
    private int payType;
    private ProgressDialog mWaitDialog;
    public CodedCouponPresenter mPresenter;

    private List<CodeCoupon> showCodeCoupons;
    private CodedCouponAdapter codedAdapter;

    private int codeType =0;//0 一维码   1二维码
    @Override
    protected int getLayoutId() {
        return R.layout.activity_coded_coupon;
    }

    @Override
    protected void initData() {
        initView();
    }

    private void initView() {
        mContext = this;
        showCodeCoupons = new ArrayList<>();
        mTicket = ErpCommonData.ticketInfo;
        payableMoney = mTicket.getTotalMoney() - mTicket.getHasPayed();
        tvOrderTotalMoney.setText(MoneyUtils.getMoneyStr(mTicket.getTotalMoney() - mTicket.getHasPayed())+"");

        Intent intent = getIntent();
        payId = intent.getIntExtra("SelectedId", 0);
        payType = intent.getIntExtra("PayType", 0);
        mWaitDialog = new ProgressDialog(mContext);
        mPresenter = new CodedCouponPresenter(this);
 //       etCodedCoupon.setOnEditorActionListener(this);

        showCodeCoupons.addAll(mTicket.getCodedCouponList());
        codedAdapter = new CodedCouponAdapter(CodedCouponActivity.this,showCodeCoupons);
        lvCodedCoupon.setAdapter(codedAdapter);
        lvCodedCoupon.setOnItemClickListener(this);
        int totalMoney =0;

        for(CodeCoupon item : mTicket.getCodedCouponList()){
            totalMoney +=item.getUsedMoney();
        }
        tvUsedTotalMoney.setText(MoneyUtils.getMoneyStr(totalMoney));
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_OK);
                finish();
            }
        });
        CommonUtils.setNoSoftware(etCodedCoupon, CodedCouponActivity.this, true);
        sf_containt.setIsCanInputPoint(false);
        sf_containt.setEnterReceptor(etCodedCoupon);
        sf_containt.setIsClearEt(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {

                    if (TextUtils.isEmpty(num)) {
                        ToastUtils.show("请输入有效编码券");
                        return ;
                    }
                    QueryMemberRequest data = new QueryMemberRequest();
                    data.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                    data.setCodedCouponType(0);
                    data.setSktno(ErpCommonData.sktno);
                    data.setCodedCouponCode(num);
                    mPresenter.getCodedCouponList(data);

            }
        });
    }

    @Override
    public void showWaitDialog(String msg) {
        mWaitDialog.setCancelable(false);
        if (mWaitDialog != null && !mWaitDialog.isShowing()) {
            mWaitDialog.setMessage(msg);
            mWaitDialog.show();
        }
    }

    @Override
    public void dismissWaitDialog() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
        }
    }

    /**
     * 获取编码券失败
     * @param msg
     */
    @Override
    public void getCodedCouponFail(String msg) {
        ToastUtils.show(msg);
    }

    /**
     * 获取编码券成功
     * @param data
     */
    @Override
    public void getCodedCouponSuccess(CodedCouponData data) {
        MessageLog.writeLog("getCodedCouponSuccess方法返回的数据长度为："+ data.getCoupons());
        etCodedCoupon.setText("");
        if(showCodeCoupons.size()>0){
            boolean isExist = false;
            for(CodeCoupon item :showCodeCoupons){//限制刷的卡之前是否存在
                if(data.getVipId() == item.getVipId()){
                    isExist = true;
                    break;
                }
            }
            if(isExist){//现在刷的卡之前刷过了
                for(CodeCoupon backItme: data.getCoupons()){// 返回的券列表
                    boolean isUsed = false;
                    for(CodeCoupon showItem :showCodeCoupons){//已经存在的券列表
                        if( backItme.getVipId() == showItem.getVipId()
                                && backItme.getCouponCode().equals(showItem.getCouponCode())
                                ){
                            isUsed = true;
                            break;
                        }
                    }
                    if(!isUsed){
                        showCodeCoupons.add(backItme);
                    }
                }
            }else{//现在刷卡的卡之前没有刷过
                showCodeCoupons.addAll(data.getCoupons());
            }
        }else{
            showCodeCoupons.addAll(data.getCoupons());
        }
        codedAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (v.getId()) {
            case R.id.et_coded_coupon:
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (TextUtils.isEmpty(etCodedCoupon.getText().toString().trim())) {
                        ToastUtils.show("请输入有效编码券");
                        return false;
                    }
                    QueryMemberRequest data = new QueryMemberRequest();
                    data.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                    data.setCodedCouponType(0);
                    data.setSktno(ErpCommonData.sktno);
                    data.setCodedCouponCode(etCodedCoupon.getText().toString().trim());
                    mPresenter.getCodedCouponList(data);
                }
                break;
        }
        return false;
    }

    /**
     * 编码券item的点击事件
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        CodeCoupon selectItem =codedAdapter.getItem(position);
        showInputCodedCouponPayedMoney(selectItem,codedAdapter);
    }

    private void showInputCodedCouponPayedMoney(final CodeCoupon selectItem, final CodedCouponAdapter codedAdapter) {

        int itemBalance = MoneyUtils.getMoneyInt(selectItem.getBalance());
        int itemLimitM = MoneyUtils.getMoneyInt(selectItem.getLimitMoney());
        //当前券最大可使用金额
        int canUseMoney = itemBalance < itemLimitM ? itemBalance:itemLimitM;
        //当前交易剩余应付金额
        int surplusPayM = ErpCommonData.ticketInfo.getTotalMoney() - ErpCommonData.ticketInfo.getHasPayed();
        //编码券已付金额(除去当前券已付金额)
        int couponPayedM = 0;
        for(CodeCoupon item :showCodeCoupons){
            if(item.getUsedMoney()!=0  &&
                    ((item.getVipId() == selectItem.getVipId() && !item.getCouponCode().equals(selectItem.getCouponCode()))
                            || (item.getVipId() != selectItem.getVipId() && item.getVipId()!=0)
                    ) ){//使用了此券
                couponPayedM += item.getUsedMoney();
            }
        }

        //卡券剩余最大应付金额
        int couponSurplusPaym = surplusPayM - couponPayedM;
        final int currentCouponMaxPay = canUseMoney >= couponSurplusPaym ? couponSurplusPaym:canUseMoney;

        InputNumberDialogCommon inputNumberDialogCommon= InputNumberDialogCommon.getInputNumberDialogCommon(CodedCouponActivity.this, new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
            @Override
            public void InputDialogOnSubmitClick(String content) {
                if(!CommonUtils.isNumber(content)){
                    ToastUtils.showMsg("请输入正确的金额！");
                }else{
                    try{
                        int inputMoney = MoneyUtils.getMoneyInt(content);
                            inputMoney=inputMoney <= currentCouponMaxPay?inputMoney:currentCouponMaxPay;
                            int currentCouponType = selectItem.getCouponType();
                            int currentCouponLimitNum = selectItem.getLimitNumber();
                            int currentUsedNum =0;
                            int useMoney=0;
                            for(CodeCoupon item :showCodeCoupons){
                                if(item.getCouponType() == currentCouponType && item.getUsedMoney() !=0 ){
                                    currentUsedNum += 1;
                                    useMoney=useMoney+item.getUsedMoney();
                                }
                            }
                            if(currentUsedNum < currentCouponLimitNum){//当前券使用数量小于该类券的限制数量
                                if((useMoney+inputMoney)<=MoneyUtils.getMoneyInt(selectItem.getLimitMoney())) {
                                    selectItem.setUsedMoney(inputMoney);
                                    codedAdapter.notifyDataSetChanged();
                                }else{
                                    ToastUtils.showMsg("券类型【"+currentCouponType+"】,最多使用金额为："+selectItem.getLimitMoney());
                                }
                            }else{
                                ToastUtils.showMsg("券类型【"+currentCouponType+"】,最多使用张数为："+currentCouponLimitNum);
                            }

                    }catch (Exception e){
                        ToastUtils.showMsg("请输入正确的金额！");
                    }
                }
            }
        });
        inputNumberDialogCommon.setEtText(MoneyUtils.getMoneyStr(currentCouponMaxPay));
        inputNumberDialogCommon.setIsCanInputPoint(true);
        inputNumberDialogCommon.setIsCanInputClear(true);
        inputNumberDialogCommon.setTitle("券使用金额");
        inputNumberDialogCommon.setContent("请输入券使用金额");
        inputNumberDialogCommon.setEtHint("请输入券使用金额");
        inputNumberDialogCommon.showDialog(false);

    }

    @OnClick({R.id.btn_codedcoupon_commit, R.id.iv_swipe_get_coded_coupon,R.id.btn_coded_coupon_saoma})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_codedcoupon_commit:
                mTicket.getCodedCouponList().clear();
                int totalCouponPayMoney = 0;
                for(CodeCoupon item :showCodeCoupons){
                    if(item.getUsedMoney()!=0){
                        mTicket.getCodedCouponList().add(item);
                        totalCouponPayMoney += item.getUsedMoney();
                    }
                }

                if(totalCouponPayMoney>0){//付款金额大于0
                    if(totalCouponPayMoney > payableMoney){
                        ToastUtils.showMsg("付款金额大于应付金额！");
                    }else {
                        setResult(RESULT_OK);
                        finish();
                    }
                }else{
                    setResult(RESULT_OK);
                    finish();
                }
                break;
            case R.id.iv_swipe_get_coded_coupon:
                PayUtil.showQueryMemberDialog(CodedCouponActivity.this, Constant.MEMBER_IDENTIFYING_CODECOUPON);
                break;
            case R.id.btn_coded_coupon_saoma://编码券扫码识别
                Intent intent = new Intent(CodedCouponActivity.this, ScanCodeActivity.class);
                startActivityForResult(intent, Constant.CODED_COUPON_SCANNER_RESULTID);
                break;
        }
    }
//    private void showCodeType() {
//        AlertDialog cancelDlg = new AlertDialog.Builder(CodedCouponActivity.this)
//                .setTitle("请选择券码类型")
//                .setCancelable(false)
//                .setPositiveButton("二维码", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        codeType =1;
//                        Intent intent = new Intent(CodedCouponActivity.this, ScanCodeActivity.class);
//                        startActivityForResult(intent, Constant.CODED_COUPON_SCANNER_RESULTID);
//                    }
//                })
//                .setNegativeButton("一维码", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        dialogInterface.dismiss();
//                        codeType =0;
//                        Intent intent = new Intent(CodedCouponActivity.this, ScanCodeActivity.class);
//                        startActivityForResult(intent, Constant.CODED_COUPON_SCANNER_RESULTID);
//                    }
//                }).create();
//        cancelDlg.show();
//    }


    /**
     * 刷卡结果
     * @param isSuccess
     * @param content
     * @param handleId
     */
    @Override
    public void doAfterSwipeCard(boolean isSuccess, String content, int handleId) {
        LogUtils.d("刷卡的结果为：" + content);
        switch (handleId) {
            case Constant.BMQ_SWIPECARD_HANDLEID: {
                if(isSuccess){
                    if (!content.equals("")) {
                        QueryMemberRequest data = new QueryMemberRequest();
                        data.setCodedCouponType(1);
                        data.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SWIPE);
                        data.setCondValue(content);
                        data.setSktno(ErpCommonData.sktno);
                        data.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                        mPresenter.getCodedCouponList(data);
                    }else{
                        ToastUtils.showMsg( "刷卡失败，请重试！");
                    }
                }else{
                    ToastUtils.showMsg("取消刷卡");
                }
            }
            break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK)
            return;
        switch (requestCode){
            case Constant.BMQ_SCAN_HANDLEID:  //会员卡扫码识别
                Bundle extras = data.getExtras();
                String content = extras.getString("Code");
                if (TextUtils.isEmpty(content))
                    return;
                if (!content.equals("")) {
                    QueryMemberRequest query = new QueryMemberRequest();
                    query.setCodedCouponType(1);
                    query.setCondType(SktConfigIdCrmConstant.SKT_CONFIG_MEMBER_TYPE_SCAN);
                    query.setCondValue(content);
                    query.setSktno(ErpCommonData.sktno);
                    query.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                    mPresenter.getCodedCouponList(query);
                }else{
                    ToastUtils.showMsg( "刷卡失败，请重试！");
                }
                break;
            case Constant.CODED_COUPON_SCANNER_RESULTID:{//编码券号扫码识别
                Bundle extrasCoded = data.getExtras();
                String code = extrasCoded.getString("Code");
                if (!TextUtils.isEmpty(code)) {
                    QueryMemberRequest data1 = new QueryMemberRequest();
                    data1.setServerBillId(Integer.parseInt(mTicket.getServerBillId()));
                    data1.setCodedCouponType(0);
                    data1.setSktno(ErpCommonData.sktno);
                    data1.setCodedCouponCode(code.trim());
                    mPresenter.getCodedCouponList(data1);
                } else {
                    Toast.makeText(this, "扫码为空，请重新扫码", Toast.LENGTH_SHORT).show();
                }
            }
            break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
